package com.lz.common.utils;

import com.lz.service.security.config.MyUserDetails;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtil {

    public static MyUserDetails getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context != null) {
            return (MyUserDetails) context.getAuthentication().getPrincipal();
        }
        return null;
    }

    public static String getId() {
        try {
            SecurityContext context = SecurityContextHolder.getContext();
            if (context != null && context.getAuthentication() != null && context.getAuthentication().isAuthenticated()) {
                Object principal = context.getAuthentication().getPrincipal();
                if (principal instanceof MyUserDetails) {
                    return ((MyUserDetails) principal).getUser().getId();
                }
            }
            return "1";
        } catch (Exception e) {
            // 可选日志记录
            return null;
        }
    }

}
